package com.example.gybicycle.controller.wx;

import com.example.gybicycle.common.entity.Result;
import com.example.gybicycle.common.redis.RedisUtil;
import com.example.gybicycle.common.util.CyclingUtil;
import com.example.gybicycle.common.util.DrawImage;
import com.example.gybicycle.common.util.LoginUtil;
import com.example.gybicycle.common.util.WeixinUtil;
import com.example.gybicycle.entity.*;
import com.example.gybicycle.entity.wx.WXLoginInfo;
import com.example.gybicycle.service.MemberService;
import com.example.gybicycle.service.SysUserService;
import com.example.gybicycle.service.wx.WLoginService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Tag(name = "登录")
@RestController
@RequestMapping("/wx")
public class WxLoginController {
    @Autowired
    private SysUserService userService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private WLoginService loginService;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.secret}")
    private String serice;
    @PostMapping("/login")
    @Operation(summary = "登录")
    @ApiOperationSupport(includeParameters = {"sysUser.name","sysUser.password"})
    public Result login(@RequestBody WXLoginInfo info, HttpServletRequest request){
        if(info.getCode()==null)
            return Result.fail("code");

        String openId= WeixinUtil.oauth2GetOpenid(appid,serice,info.getCode());
        if(openId==null)
            return Result.fail("获取openid失败");
        info.setWxOpenid(openId);
        if(info.getWxOpenid()==null)
            return Result.fail("请传输openid");

        info.setAuthorization("eqweqwej"+info.getWxOpenid());
        Member member=memberService.getByOpenId(info.getWxOpenid());
        if(member==null){
            SysUser user=userService.getByOpenId(info.getWxOpenid());
            if(user==null){
                 info.setAuthorization("eqweqwej"+openId);
                /*member=new Member();
                member.setName(info.getName());
                member.setWxOpenid(openId);
                member.setTelphone("18219231234");
                member.setGrade(3);
                member.setJoinDate(new Date());
                memberService.insert(member);
                info.setName(member.getName());
                info.setPath(CyclingUtil.cyclingPath());
                info.setId(member.getId());
                info.setType(0);
                LoginUtil.setWxLoginInfo(info);
                return Result.success(info);*/
                return Result.success(info,"账号未注册");

            }

            CyclingUtil.setWxLoginInfo(user,info);
            LoginUtil.setWxLoginInfo(info);
//            System.out.println("login-2");
//            System.out.println(LoginUtil.getWxLoginInfo(info.getAuthorization()));
            info.setPath(CyclingUtil.AdminPath());
            return Result.success(info);
        }
//        System.out.println("login-3");
        BeanUtils.copyProperties(member,info);
        info.setType(0);
        info.setPath(CyclingUtil.cyclingPath());
        LoginUtil.setWxLoginInfo(info);
//        System.out.println("login-2");
//        System.out.println(LoginUtil.getWxLoginInfo(info.getAuthorization()));
        return Result.success(info);
    }

    @PostMapping("/saveInfo")
    @Operation(summary = "保存用户信息")
    @ApiOperationSupport(includeParameters = {"sysUser.name","sysUser.password"})
    public Result saveInfo(@RequestBody WXLoginInfo info, HttpServletRequest request){
        if(info==null)
            return Result.fail("未获取用户数据");
        if(info.getCode()==null)
            return Result.fail("未获得code");
        System.out.println("save-1");
        System.out.println(info);
       String telPhone= WeixinUtil.getTelPhone(appid,serice,info.getCode());

       if(telPhone==null)
           return Result.fail("获取电话号码失败");
       if(telPhone.length()==0)
           return Result.fail("获取AccessToken失败");
       if(info.getAuthorization()==null)
           return Result.fail("请传入token");
       info=LoginUtil.getWxLoginInfo(info.getAuthorization());
//        System.out.println("save-2");
//        System.out.println(info);
       info.setTelphone(telPhone);
        SysUser user=userService.getByTelphone(info.getTelphone());
        if(user!=null){
            user.setWxNo(info.getWxOpenid());
            CyclingUtil.setWxLoginInfo(user,info);
            info.setPath(CyclingUtil.AdminPath());

            userService.update(user);
        }else {
            Member member=new Member();
            member.setName(info.getName());
            member.setWxOpenid(info.getWxOpenid());
            member.setBirthday(info.getBirthday());
            member.setWxNo(info.getWxNo());
            member.setSex(info.getSex());
            member.setTelphone(info.getTelphone());
            member.setGrade(0);
//            BeanUtils.copyProperties(member,info);
            member.setJoinDate(new Date());
            memberService.insert(member);
            info.setPath(CyclingUtil.cyclingPath());
            info.setId(member.getId());
            info.setType(0);
        }
          LoginUtil.setWxLoginInfo(info);
         return Result.success(info);

    }

    @PostMapping("/userInfo")
    @Operation(summary ="登录用户信息")
    public Result userInfo(HttpServletRequest request){
        LoginInfo info=LoginUtil.getLoginInfo(request);
        return Result.success(info);
    }


    @PostMapping("/loginout")
    @Operation(summary ="退出登录")
//    @SysLoging("登录管理-退出登录")
    public Result login( HttpServletRequest request){
        LoginUtil.wxloginout(request);
        return Result.success("退出登录成功");
    }
    @PostMapping("/uppwd")
    @Operation(summary ="修改密码")
    public Result uppwd(@RequestBody UserUpPwd pwd, HttpServletRequest request){
        WXLoginInfo info=LoginUtil.getWxLoginInfo(request);
        if(info==null)
            return Result.loginOut();
        if(!info.getType().equals(1))
            return Result.fail("当前非管理员，不能修改密码");
        SysUser user=new SysUser();
        user.setId(info.getId());
        user.setPassword(pwd.getOldpassword());
        List<SysUser> list=userService.findList(user);
        if(list.size()==1){
            user.setPassword(pwd.getPassword());
            int num=userService.update(user);
            if(num>0)
                return Result.success("修改密码成功");
        }else return Result.fail("原密码错误");
        return Result.success("修改密码失败");
    }


}
